package com.module_video.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.utls.glide.GlideConfig;
import com.lib.view.player.MyJzvdStd;
import com.luck.picture.lib.tools.ToastManage;
import com.module_video.R;
import com.module_video.R2;
import com.module_video.bean.CareStateBean;
import com.module_video.bean.CircleCollectBean;
import com.module_video.bean.CircleLikesBean;
import com.module_video.bean.ShareDetailWebReplyBean;
import com.module_video.bean.ShortVideoListCommend;
import com.module_video.popuputil.VideoDetailCommentPopup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jzvd.JzvdStd;

/**
 * Created by Administrator on 2020/7/22 0022.
 */

@Route(path = ARouterPathUtils.Tablet_Video_ShortVideoDetailActivity)
public class ShortVideoDetailActivity extends BaseAppActivity {

    @BindView(R2.id.rv_video)
    RecyclerView rvVideo;

    @BindView(R2.id.iv_back)
    ImageView ivBack;

    @Autowired(name = "teacher_id")
    int teacher_id;
    @Autowired(name = "dynamic_id")
    int dynamic_id;

    //推荐老师视频页面卡
    public int teacherPage = 0;

    //推荐视频页面卡
    public int recommendPage = 0;

    ShortVideoAdapter shortVideoAdapter;
    List<ShortVideoListCommend.ObjBean.RowsBean> mDataList = new ArrayList();

    //用于判断老师视频是否已经没有了  true代表已结束
    public boolean isTeacherVideoFinish = false;

    VideoDetailCommentPopup commentPopup;


    @Override
    protected void onCreateView() {

        dynamic_id = getIntent().getIntExtra("dynamic_id", -1);
        teacher_id = getIntent().getIntExtra("teacher_id", -1);

        initUI();

        //获取指定动态id的视频详情
        initDynamicIdVideoInfo();

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        destroyAllData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        destroyAllData();
    }

    public void destroyAllData() {
        //销毁所有数据
        dynamic_id = -1;
        teacher_id = -1;

        teacherPage = -1;
        recommendPage = -1;

        if (mDataList != null) {
            mDataList.clear();
            mDataList = null;
        }

        if (shortVideoAdapter != null) {
            shortVideoAdapter = null;
        }

        if (rvVideo != null) {
            View view = rvVideo.getChildAt(0);
            if (view != null) {
                final MyJzvdStd videoView = view.findViewById(R.id.detail_jzplayer);
                videoView.goOnPlayOnPause();
            }
            currrntPosi = -1;
            view = null;

            rvVideo.removeAllViews();
            rvVideo = null;
        }
    }


    //用于记录当前视频位置
    int currrntPosi = -1;

    public void initUI() {
        // ---RecyclerView---
        rvVideo.setNestedScrollingEnabled(false);
        // PagerSnapHelper
        PagerSnapHelper snapHelper = new PagerSnapHelper() {
            // 在 Adapter的 onBindViewHolder 之后执行
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                // TODO 找到对应的Index
                LogUtil.e("mDataList.size() = " + mDataList.size());
                LogUtil.e("layoutManager.getChildCount = " + layoutManager.getChildCount());
                //获取当前item的位置，从0开始
                int targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                LogUtil.e("targetPos = " + targetPos);

                currrntPosi = targetPos;
                //如果滑动到底部，则刷新数据
                if (targetPos == mDataList.size()) {
                    //如果该老师已无视频，则加载推荐视频
                    if (isTeacherVideoFinish) {
                        getRecommendShortVideoList();
                        ++recommendPage;
                    } else {
                        getTeacherShortVideoList();
                        ++teacherPage;
                    }
                    LogUtil.e("已经滑动到底部了，你可停手吧");
                }
                return targetPos;
            }

            // 在 Adapter的 onBindViewHolder 之后执行
            @Nullable
            @Override
            public View findSnapView(RecyclerView.LayoutManager layoutManager) {
                // TODO 找到对应的View
                LogUtil.e("---findSnapView---");

                if (currrntPosi - 1 > 0 || currrntPosi - 1 == 0) {
                    View itemView = layoutManager.getChildAt(currrntPosi);
                    if (itemView != null) {
                        final MyJzvdStd videoView = itemView.findViewById(R.id.detail_jzplayer);
                        videoView.goOnPlayOnPause();
                    }
                }

                View view = super.findSnapView(layoutManager);
                LogUtil.e("tag: " + view.getTag());
                return view;
            }
        };
        snapHelper.attachToRecyclerView(rvVideo);
        // ---布局管理器---
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        // 默认是Vertical (HORIZONTAL则为横向列表)
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //
        rvVideo.setLayoutManager(linearLayoutManager);

        shortVideoAdapter = new ShortVideoAdapter(this, mDataList);
        // 设置Adapter
        rvVideo.setAdapter(shortVideoAdapter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shortvideodetail;
    }


    private void initDynamicIdVideoInfo() {

        HttpUtils.with(this)
                .addParam("requestType", "GET_SHORT_VIDEO_DETAILS")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("dynamic_id", dynamic_id)
                .execute(new HttpNormalCallBack<ShortVideoListCommend>() {
                    @Override
                    public void onSuccess(ShortVideoListCommend result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj().getRows().size() > 0 && result.getObj().getRows() != null) {
                                mDataList.addAll(result.getObj().getRows());
                                shortVideoAdapter.notifyDataSetChanged();
//                                initListener();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    /**
     * 获取除了某老师之外的所有推荐的短视频
     */
    private void getRecommendShortVideoList() {

        HttpUtils.with(this)
                .addParam("requestType", "TEACHER_VIDEO_RECOMMENDATION")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("teacher_id", teacher_id)
                .addParam("page", recommendPage)
                .addParam("limit", 10)
                .execute(new HttpNormalCallBack<ShortVideoListCommend>() {
                    @Override
                    public void onSuccess(ShortVideoListCommend result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj().getRows().size() > 0 && result.getObj().getRows() != null) {
                                mDataList.addAll(result.getObj().getRows());
                                shortVideoAdapter.notifyDataSetChanged();
//                                initListener();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    /**
     * 获取该老师除了本视频以外其他所有的视频
     */
    private void getTeacherShortVideoList() {

        HttpUtils.with(this)
                .addParam("requestType", "TEACHER_ALL_SHORT_VIDEOS")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("page", teacherPage)
                .addParam("limit", 10)
                .addParam("teacher_id", teacher_id)
                .addParam("dynamic_id", dynamic_id)
                .execute(new HttpNormalCallBack<ShortVideoListCommend>() {
                    @Override
                    public void onSuccess(ShortVideoListCommend result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj().getRows().size() > 0 && result.getObj().getRows() != null) {
                                if (result.getObj().getRows().size() < 10) {
                                    //如果本次视频不足10条，则下次便不在加载本接口
                                    isTeacherVideoFinish = true;
                                }
                                mDataList.addAll(result.getObj().getRows());
                                shortVideoAdapter.notifyDataSetChanged();
//                                initListener();
                            } else if (result.getObj().getRows().size() == 0) {//如果老师视频为空，则加载推荐视频
                                getRecommendShortVideoList();
                                ++recommendPage;
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }


    class ShortVideoAdapter extends BaseAdapter<ShortVideoListCommend.ObjBean.RowsBean> {

        public ShortVideoAdapter(Context context, List<ShortVideoListCommend.ObjBean.RowsBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_shortvideodetail;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, final int position, final List<ShortVideoListCommend.ObjBean.RowsBean> mData) {

            final ShortVideoListCommend.ObjBean.RowsBean rowsBean = mData.get(position);
            final MyJzvdStd jzvdStd = holder.getView(R.id.detail_jzplayer);
            if (StringUtil.isNotEmpty(rowsBean.getDynamic_hash(), true)) {
                //设置容器内播放器高,解决黑边（视频全屏）
                jzvdStd.setVideoImageDisplayType(JzvdStd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT);
                jzvdStd.TOOL_BAR_EXIST = false;
                jzvdStd.fullscreenButton.setVisibility(View.GONE);
                jzvdStd.setUp(rowsBean.getDynamic_hash(), "");
                Glide.with(ShortVideoDetailActivity.this).load(rowsBean.getDynamic_hash_icon())
                        .into(jzvdStd.thumbImageView);
                jzvdStd.startVideo();
            }

            //视频作者头像
            ImageView ivUser = holder.getView(R.id.iv_user);
            if (StringUtil.isNotEmpty(rowsBean.getPhoto_url(), true)) {
                Glide.with(ShortVideoDetailActivity.this)
                        .load(rowsBean.getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }
            ivUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance().build(ARouterPathUtils.Tablet_User_InfoActivity)
                            .withInt("teacherId", rowsBean.getUser_id()).navigation();
                }
            });

            //视频作者名称
            if (StringUtil.isNotEmpty(rowsBean.getUser_name(), true)) {
                holder.setText(R.id.tv_name, rowsBean.getUser_name());
            }
            //视频简介
            if (StringUtil.isNotEmpty(rowsBean.getDynamic_content(), true)) {
                holder.setText(R.id.tv_content, rowsBean.getDynamic_content());
            }
            //设置关注状态
            final TextView tvState = holder.getView(R.id.tv_video_care);
            if (rowsBean.getAttention_status() > -1) {
                if (1 == rowsBean.getAttention_status()) {
                    tvState.setText("已关注");
                    tvState.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                    tvState.setTextColor(getResources().getColor(R.color.newshare_care));
                }
            }
            tvState.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //传递关注/取关到服务器
                    sendCareStateToService(tvState, rowsBean.getUser_id());
                }
            });

            //收藏、评论、点赞数量及收藏、点赞状态
            final TextView tvCollectTotal = holder.getView(R.id.tv_collcet);
            if (StringUtil.isNotEmpty(rowsBean.getFavorites_total() + "", true)) {
                tvCollectTotal.setText(rowsBean.getFavorites_total() + "");
            }
            final TextView tvLikeTotal = holder.getView(R.id.tv_zan);
            if (StringUtil.isNotEmpty(rowsBean.getLike_total() + "", true)) {
                tvLikeTotal.setText(rowsBean.getLike_total() + "");
            }

            if (StringUtil.isNotEmpty(rowsBean.getComment_total() + "", true)) {
                holder.setText(R.id.tv_comment, rowsBean.getComment_total() + "");
            }
            LinearLayout linComment = holder.getView(R.id.lin_comment);
            linComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String videoJson = MGson.newGson().toJson(rowsBean);
                    LogUtil.e("传递的videoJson数据为：" + videoJson);
                    commentPopup = new VideoDetailCommentPopup(ShortVideoDetailActivity.this, view, videoJson);
                    commentPopup.showAnswerPopuPopu(view);
                }
            });

            //设置点赞、收藏状态
            final ImageView ivCollcet = holder.getView(R.id.iv_collcet);
            if (rowsBean.getFavorits_status() > -1) {
                if (1 == rowsBean.getFavorits_status()) {
                    ivCollcet.setImageResource(R.mipmap.icon_collection);
                }
            }
            ivCollcet.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendCollectToService(rowsBean.getDynamic_id(), ivCollcet, tvCollectTotal);
                }
            });

            final ImageView ivLike = holder.getView(R.id.iv_zan);
            if (rowsBean.getLike_status() > -1) {
                if (1 == rowsBean.getLike_status()) {
                    ivLike.setImageResource(R.mipmap.circle_icon_like_s_have);
                }
            }
            ivLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendLikesToService(rowsBean.getDynamic_id(), ivLike, tvLikeTotal);
                }
            });

            final EditText etMsg = holder.getView(R.id.et_message);
            LinearLayout linsend = holder.getView(R.id.lin_send);
            linsend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (StringUtil.isNotEmpty(etMsg.getText().toString().trim(), true)) {
                        sendReplyCommentToService(etMsg.getText().toString().trim(), rowsBean.getDynamic_id());
                    } else {
                        showToast("请先输入您想说的话哦！");
                    }
                }
            });

        }
    }


    /**
     * 发送一级评论消息至后台
     *
     * @param replyMsg
     */
    private void sendReplyCommentToService(String replyMsg, int dynamic_id) {

        HttpUtils.with(this)
                .addParam("requestType", "DYNAMIC_COMMENT")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("comment_content", replyMsg)
                .addParam("dynamic_id", dynamic_id)
                .execute(new HttpDialogCallBack<ShareDetailWebReplyBean>() {
                    @Override
                    public void onSuccess(ShareDetailWebReplyBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());

                        } else {
                            ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void sendLikesToService(int dynamic_id, final ImageView ivLikes, final TextView tvLikeTotal) {

        LogUtil.e("请求DYNAMIC_LIKE接口时，dynamic_id的值为：" + dynamic_id);
        if (dynamic_id != 0)
            HttpUtils.with(this)
                    .addParam("requestType", "DYNAMIC_LIKE")
                    .addParam("dynamic_id", dynamic_id)
                    .addParam("token", SharedPreferenceManager.getInstance(ShortVideoDetailActivity.this).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<CircleLikesBean>() {
                        @Override
                        public void onSuccess(CircleLikesBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                int zan = result.getObj().getLike_status();

                                if (1 == zan) {
                                    ivLikes.setImageResource(R.mipmap.circle_icon_like_s_have);
                                } else if (0 == zan) {
                                    ivLikes.setImageResource(R.mipmap.circle_icon_like_s_none);
                                }
                                tvLikeTotal.setText(result.getObj().getLike_total() + "");
                                ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());

                            } else {
                                ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });

    }

    private void sendCollectToService(int dynamic_id, final ImageView ivCollect, final TextView tvCollectTotal) {

        LogUtil.e("请求DYNAMIC_LIKE接口时，dynamic_id的值为：" + dynamic_id);
        if (dynamic_id != 0)
            HttpUtils.with(this)
                    .addParam("requestType", "DYNAMIC_FAVORITES")
                    .addParam("dynamic_id", dynamic_id)
                    .addParam("token", SharedPreferenceManager.getInstance(ShortVideoDetailActivity.this).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<CircleCollectBean>() {
                        @Override
                        public void onSuccess(CircleCollectBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                int zan = result.getObj().getAttention_status();

                                if (1 == zan) {
                                    ivCollect.setImageResource(R.mipmap.icon_collection);
                                } else if (0 == zan) {
                                    ivCollect.setImageResource(R.mipmap.icon_wcollection);
                                }
                                tvCollectTotal.setText(result.getObj().getTotal() + "");
                                ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());

                            } else {
                                ToastManage.s(ShortVideoDetailActivity.this, result.getMsg());
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });
    }

    public void sendCareStateToService(final TextView tvCare, int userId) {

        HttpUtils.with(ShortVideoDetailActivity.this)
                .addParam("requestType", "DYNAMIC_ATTENTION")
                .addParam("be_user_id", userId + "")
                .addParam("token", SharedPreferenceManager.getInstance(ShortVideoDetailActivity.this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<CareStateBean>() {
                    @Override
                    public void onSuccess(CareStateBean result) {

                        if (result != null) {
                            if (CodeUtil.CODE_200 == result.getCode()) {
                                if (0 == result.getObj().getAttention_status()) {
                                    tvCare.setText("关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_care_r_20);
                                    tvCare.setTextColor(getResources().getColor(R.color.white));

                                } else if (1 == result.getObj().getAttention_status()) {
                                    tvCare.setText("已关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                                    tvCare.setTextColor(getResources().getColor(R.color.newshare_care));
                                }
                                showToast(result.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {
                        LogUtil.e(e.toString());
                    }
                });
    }
}
